from PySide6.QtWidgets import QApplication, QWidget, QFileDialog
from Ui_花卉分类识别 import Ui_Form
from PySide6.QtGui import QPixmap,QDesktopServices
from PySide6.QtCore import Qt,QUrl
import os
import datetime
from recognition import recognize_flower
import shutil

class FlowerRecognitionApp(QWidget):

    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        # 绑定信号与槽
        self.bind()
        # 初始化图片路径
        self.image_path = None
        # 定义历史文件路径
        self.history_path = "recognize_history"
        # 确保历史文件夹存在
        os.makedirs(self.history_path, exist_ok=True)

    def bind(self):
        self.ui.up_pushButton.clicked.connect(self.upload_image)
        self.ui.recognize_pushButton.clicked.connect(self.recognize_image)
        self.ui.history_pushButton.clicked.connect(self.open_history_folder)

    def upload_image(self):
        file_path,_ = QFileDialog.getOpenFileName(self,"选择图片","","Images (*.png *.jpg *.jpeg *.bmp)")
        if file_path:
            self.image_path = file_path
            pixmap = QPixmap(file_path)
            self.ui.image_label.setPixmap(pixmap.scaled(self.ui.image_label.size(), Qt.KeepAspectRatio))


    def recognize_image(self):
        if self.image_path:
            # 获取识别结果
            result = recognize_flower(self.image_path)
            self.ui.result_label.setText(f"识别结果：{result}")

            # 保存图片到历史文件夹
            timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            file_extension = os.path.splitext(self.image_path)[1]
            save_path = os.path.join(self.history_path,f"{result}{timestamp}{file_extension}")

            try:
                # 使用 shutil 模块复制文件
                shutil.copy(self.image_path,save_path)
                print(f"已保存图片到历史文件夹：{save_path}")
            except Exception as e:
                print(f"保存图片时出错：{e}")

    def open_history_folder(self):
        QDesktopServices.openUrl(QUrl.fromLocalFile(self.history_path))

if __name__=="__main__":
    app = QApplication([])
    window = FlowerRecognitionApp()
    window.show()
    app.exec()